﻿// <copyright file="HashExtensions.cs" company="DotNetLib">
//
// .netlib: http://www.codeplex.com/DotNetLib
//
// This code is released under the New BSD License.
// A copy of this license is available at:
// http://www.codeplex.com/DotNetLib/license
//
// </copyright>

namespace DotNetLib.Security
{
  using System;
  using System.Security.Cryptography;
  using System.Text;

  /// <summary>
  /// Extension methods for producing hashes.
  /// </summary>
  public static class HashExtensions
  {
    /// <summary>
    /// Computes the hash of the byte array using the specified hashing algorithm.
    /// </summary>
    /// <param name="value">The array to hash.</param>
    /// <param name="hashType">The hash algorithm to use.</param>
    /// <returns>The hashed value.</returns>
    public static byte[] ComputeHash(this byte[] value, HashType hashType)
    {
      HashAlgorithm hash = CreateHashAlgorithm(hashType);
      return hash.ComputeHash(value);
    }

    /// <summary>
    /// Computes the hash of the string using the default <see cref="Encoding"/> and the specified hashing algorithm.
    /// </summary>
    /// <param name="value">The string to hash.</param>
    /// <param name="hashType">The hash algorithm to use.</param>
    /// <returns>The hashed value.</returns>
    public static byte[] ComputeHash(this string value, HashType hashType)
    {
      return ComputeHash(Encoding.Default.GetBytes(value), hashType);
    }

    /// <summary>
    /// Creates the appropriate hashing algorithm.
    /// </summary>
    /// <param name="hashType">The hashing algorithm to create.</param>
    /// <returns>The hashing algorithm.</returns>
    private static HashAlgorithm CreateHashAlgorithm(HashType hashType)
    {
      switch (hashType)
      {
        case HashType.MD5:
          return MD5.Create();
        case HashType.SHA:
          return SHA1.Create();
        case HashType.SHA256:
          return SHA256.Create();
        case HashType.SHA384:
          return SHA384.Create();
        case HashType.SHA512:
          return SHA512.Create();
        default:
          throw new ArgumentOutOfRangeException("hashType");
      }
    }
  }
}
